package com.hwl.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwl.commonutils.utils.AssertUtil;
import com.hwl.eduservice.mapper.ChapterMapper;
import com.hwl.eduservice.mapper.VideoMapper;
import com.hwl.eduservice.pojo.Chapter;
import com.hwl.eduservice.pojo.Video;
import com.hwl.eduservice.pojo.vo.VideoVo;
import com.hwl.eduservice.service.ChapterService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author long
 * @since 2021-09-21
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Resource
    private VideoMapper videoMapper;

    @Override
    public boolean removeChapterById(String chapterId) {
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<Video>().eq("chapter_id", chapterId);
        AssertUtil.isTrue(videoMapper.selectCount(videoQueryWrapper) > 0, "删除失败！该章节下还有其他小节~");

        return this.removeById(chapterId);
    }

    @Override
    public List<Chapter> getAllChapter(String courseId) {
        //获取所有的章节
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<Chapter>()
                .eq("course_id", courseId).orderByAsc("sort", "id");
        List<Chapter> chapters = baseMapper.selectList(chapterQueryWrapper);

        //获取所有的小节
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<Video>()
                .eq("course_id", courseId).orderByAsc("sort", "id");
        List<Video> videos = videoMapper.selectList(videoQueryWrapper);

        for (Chapter chapter : chapters) {
            List<VideoVo> videoVos = new ArrayList<>(); //准备集合
            videos.forEach(video -> {
                if (chapter.getId().equals(video.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);

                    videoVos.add(videoVo);
                }
            });
            chapter.setChildren(videoVos);
        }

        return chapters;
    }
}
